<template>
  <view class="container">
    <unicloud-db ref="udb" @load="handleLoad" v-slot:default="{data, loading, error, options}" :options="options" :collection="collectionList" field="deviceId,room,num,baseInfo,ip,espmac,health" :where="queryWhere" :getone="true" :manual="true">
      <view v-if="error">{{error.message}}</view>
      <view v-else-if="loading">
        <uni-load-more :contentText="loadMore" status="loading"></uni-load-more>
      </view>
      <view v-else-if="data">
				<view class="mDevice">
					<view class="mDeviceItem redText">
					  <text>设备编号：</text>
					  <text>{{data.deviceId._value}}</text>
					</view>
					<view class="mDeviceItem">
					  <text>机房名称：</text>
					  <text>{{data.room}}</text>
					</view>
					<view class="mDeviceItem">
					  <text>位置序号：</text>
					  <text>{{data.num}}</text>
					</view>
					<view class="mDeviceItem">
					  <text>设备单价：</text>
					  <text>{{data.baseInfo.price}}</text>
					</view>
					<view class="mDeviceItem">
					  <text>生产厂家：</text>
					  <text>{{data.baseInfo.productor}}</text>
					</view>
					<view class="mDeviceItem">
					  <text >购置日期：</text>
					  <text>{{data.baseInfo.buyDate}}</text>
					</view>
					<view class="mDeviceItem">
					  <text>IP 地 址 ：</text>
					  <text>{{data.ip}}</text>
					</view>
					<view class="mDeviceItem">
					  <text>插座地址：</text>
					  <text>{{data.espmac[0].mac}}</text>
					</view>
					<view class="mDeviceItem">
					  <text>设备状态：</text>
					  <text>{{data.health == true ? '✅' : '❌'}}</text>
						
					</view>
					<view class="mDeviceItem">
						<text>控制操作：</text>
						
						<view class="mybutton" v-if="powerOn">
							<u-button type="primary" style="width: 100px;" size="small" :plain="true" text="网络检查"
								@click="netCheck(mac,ip,num)"></u-button>
								
							<u-button type="warning" style="width: 100px;" size="small" :plain="true" text="关闭电源"
							@click="powerChange(mac,num)"></u-button>
						</view>
						<view v-else>
							<u-button type="success" style="width: 100px;" size="small" :plain="true" text="打开电源"
							@click="powerChange(mac,num)"></u-button>
						</view>
					</view>
				</view>
        
				<view class="btns">
					<view v-if="data.health == true">
						<button type="primary" @click="handleUpdate(deviceId)">故障报修</button>
					</view>
					<view v-else>
						<button type="warn" class="btn-delete" @click="handleDelete">故障已解决</button>
					</view>  
				</view>
				
				<view class="breakInfo">
					<view v-if="data.deviceId.breaks.length>0">
						<view class="breaksHead">
							<u--image src="/static/watchout.png" width="32px" height="32px"></u--image>
							<text>故障信息列表</text>
						</view>
					  <uni-list>
					    <uni-list-item v-for="(item, index) in data.deviceId.breaks" :key="index" showArrow :clickable="true" @click="handleItemClick(item._id)">
					      <template v-slot:body>
					        <uni-dateformat :threshold="[0, 0]" :date="item.subtime"></uni-dateformat>
					      </template>
					    </uni-list-item>
					  </uni-list>
					</view>
					
				</view>
      </view>
    </unicloud-db>
  </view>
</template>

<script>
	import { WSNRTConnect } from '@/static/WSN/WSNRTConnect.js'
  // 由schema2code生成，包含校验规则和enum静态数据
  import { enumConverter } from '../../js_sdk/validator/pc-info.js'
  const db = uniCloud.database()

  export default {
		watch: {
			myMessage(){
				uni.showToast({
					title: this.myMessage,
					duration: 500
				})
			},
			myNetStatus(){
				if(this.index > 0){
					let showMessage = this.myNetStatus.substr(0,8)
					uni.showToast({
						title: showMessage,
						duration: 500
					})
				}
			}
		},
    data() {
      return {
				deviceId:"",
				zonesionId:"",
				zonesionKey:"",
				mac:"",
				num:"",
				ip:"",
				powerOn: false,
				myMessage: "",
				myNetStatus: "",
				index:0,
				addr: "api.zhiyun360.com",
				rtc: null,
        queryWhere: '',
        collectionList: "pc-info,espmac,breaks",
        loadMore: {
          contentdown: '',
          contentrefresh: '',
          contentnomore: ''
        },
        options: {
          // 将scheme enum 属性静态数据中的value转成text
          ...enumConverter
        }
      }
    },
    onLoad(e) {
      this._id = e.id
    },
    onReady() {
      if (this._id) {
        this.queryWhere = '_id=="' + this._id + '"'
      }
    },
		
    methods: {
			handleLoad(data, ended, pagination) {
				this.deviceId = data.deviceId._value
				this.zonesionId = data.espmac[0].zonesionId
				this.zonesionKey = data.espmac[0].zonesionKey
				this.ip = data.ip
				this.mac = data.espmac[0].mac
				this.num = data.num
				this.getConnect(this.zonesionId, this.zonesionKey, this.mac, this.num)
			},
			getConnect(id, key, espmac, num){
				let m = (num - 1) % 4
				let d = Math.pow(2, m)
				this.rtc = new WSNRTConnect(id, key)  
				this.rtc.setServerAddr(this.addr)               
				this.rtc.connect()                              
				this.rtc.onConnect = () => {                    
					//this.myMessage = '数据服务连接成功...'
					console.log('数据服务连接成功hhh...')
					this.rtc.sendMessage(espmac, '{OD1=1,D1=?}')    
				}
				this.rtc.onConnectLost = () => {               
					console.log('数据服务连接失败...')
					//this.myMessage = '数据服务连接失败...'
				};
				this.rtc.onmessageArrive = (mac, data) => {     
				console.log(data)
					if (data[0] == '{' && data[data.length - 1] == '}') {     
						let its = data.slice(1,-1).split(',')   
						for (let i = 0; i < its.length; i++) {  
							let t = its[i].split("=")           
							if (t.length != 2) continue		   
							//console.log({mac},its);
							if (mac == espmac) {				
								if (t[0] == 'D1') {          	
									if(t[1] & d) {
										this.powerOn = true
										this.myMessage = "电源已打开"
									} else {
										this.powerOn = false
										this.myMessage = "电源已关闭"
									}
								}
								if (t[0] == 'A0' || t[0] == 'A1' || t[0] == 'A2' || t[0] == 'A3') {          
									if(t[1] == 1) {
										this.myNetStatus = "网络正常" + this.index
									} else {
										this.myNetStatus = "网络断开" + this.index
									}
								}
							}
						}
					}
				}
			},
			netCheck(mac, ip, num){
				this.index++
				let m = (num - 1) % 4
				if(this.powerOn){
					this.rtc.sendMessage(mac, '{V1='+ip+'}')
					var that = this
					setTimeout(()=>{
						that.rtc.sendMessage(mac, '{A'+m+'=?}')
					},5000)
				}else{
					this.myMessage = "请先打开电源"
				}
			},
			powerChange(mac, num){
				let m = (num - 1) % 4
				let d = Math.pow(2, m)
				if(this.powerOn){
					this.rtc.sendMessage(mac, '{CD1='+d+',D1=?}')
				}else{
					this.rtc.sendMessage(mac, '{OD1='+d+',D1=?}')
				}
			},
      handleUpdate(deviceId) {
				db.collection('pc-info')
					.doc(this._id)
					.update({health:false})
					.then((res)=>{
						uni.showToast({
							title:"状态已更新",
							duration:2000
						})
						setTimeout(()=>{
								uni.navigateTo({
									url:'/pages/breaks/add?deviceId='+deviceId
								})
						},2000)
					})
      },
      handleDelete() {
				db.collection('pc-info').doc(this._id).update({health:true}).then((res)=>{
					uni.showToast({
						title:"状态已更新",
						duration:2000
					})
					setTimeout(()=>{
							uni.navigateTo({
								url:'/pages/pc-info/list'
							})
					},2000)
				})
      },
			handleItemClick(id) {
			  uni.navigateTo({
			    url: "/pages/breaks/detail?id=" + id
			  })
			}
    }
  }
</script>

<style>
  .container {
    padding: 10px;
  }
	.mDevice{
		display: flex;
		flex-direction: column;
		width: 100%;
		background-color: #F7F7F7;
		border: 1px solid #999;
		border-radius: 5px;
	}
	.mDeviceItem{
		display: flex;
		flex-direction: row;
		padding: 5px 15px;
		border-bottom: 1px dotted #999;
		color: #666;
	}
	.mybutton{
		display: flex;
		flex-direction: row;
	}
	.redText{
		color: #FF0000;
	}

  .btns {
    margin-top: 10px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
  }

  .btns button {
    flex: 1;
  }

  .btn-delete {
    margin-left: 10px;
  }
	
	.breaksHead{
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 100%;
		height: 40px;
		line-height: 40px;
		padding: 10px 15px;
		font-size: 18px;
		color: #666;
	}
</style>
